# encoding: utf-8
# 项目名称： drf-simple
# @File  : hooks.py
# @Author: sun hao
# @Desc : 
# @Date  :   20:14 2025/05/08
from rest_framework.fields import SkipField
from rest_framework.relations import PKOnlyObject  # NOQA # isort:skip


class HooksSerializer(object):
    def to_representation(self, instance):
        """
            这里直接重写源码类的to_representation 方法，多加一个if判断
        """
        ret = {}
        fields = self._readable_fields
        for field in fields:
            if hasattr(self, "get_%s" % field.field_name):
                value = getattr(self, "get_%s" % field.field_name)(instance)
                ret[field.field_name] = value
            else:
                try:
                    attribute = field.get_attribute(instance)
                except SkipField:
                    continue
                check_for_none = attribute.pk if isinstance(attribute, PKOnlyObject) else attribute
                if check_for_none is None:
                    ret[field.field_name] = None
                else:
                    ret[field.field_name] = field.to_representation(attribute)
        return ret
